package com.nyt.report.config;

import com.nyt.report.constant.CityCodes;
import com.nyt.report.constant.Methods;
import org.apache.kafka.clients.admin.AdminClient;
import org.apache.kafka.clients.admin.CreateTopicsResult;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * 定义应用启动时的任务
 */
@Configuration
public class JobAtBoot implements CommandLineRunner{

    @Autowired
    AdminClient adminClient;

    @Override
    public void run(String... args) throws Exception {
        // 检查是否创建kafka队列，没有就创建
        List<NewTopic> topics = new ArrayList<>();
        for (String method : Methods.syncMethod().keySet()) {
            topics.add(new NewTopic(method, 2, (short) 1));
        }
//        for (String cityPrefix : CityCodes.keySet()) {
//            for (String method : Methods.syncMethod().keySet()) {
//                topics.add(new NewTopic(cityPrefix + "_" + method, 2, (short) 1));
//            }
//        }
        try {
            CreateTopicsResult result = adminClient.createTopics(topics);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            adminClient.close();
        }
    }
}
